package hanjia;

/**
 * Description:
 * Author:    Dane
 * CreateTime:2025/2/9-下午5:43
 * Since  :   1.0
 * Version:   1.0
 */
public class LeetCode176 {

    public static boolean isBalanced(TreeNode root) {
            if (root==null){
                return true;
            }
            int left=maxDepth(root.left);
            int right=maxDepth(root.right);
            int result=Math.abs(left-right);
            if (result>1){
                return false;
            }

           if (isBalanced(root.left)&&isBalanced(root.right)){
               return true;
           }
           return false;


    }


    public static int maxDepth(TreeNode root) {

        if (root==null){
            return 0;
        }

        return Math.max(maxDepth(root.left),maxDepth((root.right)))+1;
    }

    public static void main(String[] args) {
        Integer[] arr = {3, 9, 20, null, null, 15, 7};
        TreeNode root = buildTree2(arr);
        isBalanced(root);
    }

    public static TreeNode buildTree2(Integer[] arr) {
        if (arr == null || arr.length == 0) {
            return null;
        }
        TreeNode root = new TreeNode(arr[0]);
        java.util.LinkedList<TreeNode> queue = new java.util.LinkedList<>();
        queue.add(root);
        int index = 1;
        while (!queue.isEmpty() && index < arr.length) {
            TreeNode node = queue.poll();
            if (arr[index] != null) {
                node.left = new TreeNode(arr[index]);
                queue.add(node.left);
            }
            index++;
            if (index < arr.length && arr[index] != null) {
                node.right = new TreeNode(arr[index]);
                queue.add(node.right);
            }
            index++;
        }
        return root;
    }

}
